<template>
  <div>
    <div style="width: 500px" class="mt-32 m-auto">
      <el-form :model="state.form" :rules="rules" ref="ruleForm">
        <el-form-item label="原密码：" label-width="100px" prop="oldPassword">
          <el-input
            type="password"
            v-model="state.form.oldPassword"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="新密码：" label-width="100px" prop="newPassword">
          <el-input
            type="password"
            v-model="state.form.newPassword"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="确认密码："
          label-width="100px"
          prop="confirmPassword"
        >
          <el-input
            type="password"
            v-model="state.form.confirmPassword"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <div style="margin-left: 100px">
          <el-button @click="state.form = {}" class="w-48">取 消</el-button>
          <el-button type="primary" @click="submitForm" class="w-48">
            确 定
          </el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>
<script setup>
import { reactive, ref } from "vue";
const ruleForm = ref(null);
const state = reactive({
  form: {},
});

const validatePass = (rule, value, callback) => {
  if (
    !/^[a-z_A-Z0-9-\.!@#\$%\\\^&\*\)\(\+=\{\}\[\]\/",'<>~\·`\?:;|]+$/.test(
      value
    )
  ) {
    callback(new Error("只能输入英文、数字、符号"));
  } else {
    if (/^[0-9]*$/.test(value)) {
      callback(new Error("不能为纯数字"));
    }
    callback();
  }
};

const validateConfirm = (rule, value, callback) => {
  if (value != state.form.newPassword) {
    callback(new Error("两次输入密码不一致"));
  } else {
    callback();
  }
};

const rules = {
  oldPassword: [
    { required: true, message: "请输入原密码", trigger: "blur" },
    { min: 8, max: 20, message: "长度再8~20字符", trigger: "blur" },
    { validator: validatePass, trigger: "blur" },
  ],
  newPassword: [
    { required: true, message: "请输入新密码", trigger: "blur" },
    { min: 8, max: 20, message: "长度再8~20字符", trigger: "blur" },
    { validator: validatePass, trigger: "blur" },
  ],
  confirmPassword: [
    { required: true, message: "请输入确认密码", trigger: "blur" },
    { min: 8, max: 20, message: "长度再8~20字符", trigger: "blur" },
    { validator: validatePass, trigger: "blur" },
    { validator: validateConfirm, trigger: "blur" },
  ],
};

function submitForm() {
  ruleForm.value.validate((valid) => {
    if (valid) {
      console.log(state.form);
      alert("submit!");
    } else {
      console.log("error submit!!");
      return false;
    }
  });
}
</script>
